package net.htjs.mobile.nyoa.gw;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;

import net.htjs.mobile.nyoa.LoginActivity;
import net.htjs.mobile.nyoa.R;
import net.htjs.mobile.nyoa.subview.FileDownLoad;
import net.htjs.mobile.nyoa.util.FileDownLoadThread;
import net.htjs.mobile.nyoa.util.L;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ListGwWebView extends Activity {
	private WebView webView;
	ProgressDialog progressDialog;

	public void onCreate(Bundle b) {
		super.onCreate(b);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		this.setContentView(R.layout.gw_webview);
		
		webView = (WebView) this.findViewById(R.id.webviewFirst);
		webView.getSettings().setJavaScriptEnabled(true);
		progressDialog = new ProgressDialog(ListGwWebView.this);// 生成一个进度条
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle("请稍等");
		progressDialog.setMessage("正在读取数据中!");
		final GetListHandler handler = new GetListHandler();
		progressDialog.show();
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if(url.contains("main.jsp")||url.contains("/server/3g/index.jsp")){
					finish();
					//webView.onKeyDown(KeyEvent.KEYCODE_BACK, null);
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				if(!progressDialog.isShowing())progressDialog.show();
				if(url.contains("/server/3g/index.jsp")){
					Intent intent = new Intent();
					intent.setClass(ListGwWebView.this, LoginActivity.class);
					startActivity(intent);
					return;
				}else if(url.contains("main.jsp")){
					finish();
					//webView.onKeyDown(KeyEvent.KEYCODE_BACK, null);
					return;
				}else if(url.contains("fileDown.jsp")){
					Intent intent = new Intent();

					Bundle bundle = new Bundle();

					bundle.putString(L.FileDownLoad.URL, url);
					bundle.putString(L.FileDownLoad.FILENAME, url.substring(url.lastIndexOf("=")));
					bundle.putString(L.FileDownLoad.FILETYPE, ".doc");
					intent.setClass(ListGwWebView.this, FileDownLoad.class);

					intent.putExtras(bundle);

					startActivity(intent);
					return;
				}
				super.onPageStarted(view, url, favicon);
			}

			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					public void run() {
						// TODO Auto-generated method stub
						Message msg = handler.obtainMessage();
						handler.sendMessage(msg);
					}
					
				}).start();
				super.onPageFinished(view, url);
				
			}
		});

		Cookie sessionCookie = L.cookie; // 这里的cookie就是上面保存的cookie
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		if (sessionCookie != null) {
			// cookieManager.removeSessionCookie();
			String cookieString = sessionCookie.getName() + "="
					+ sessionCookie.getValue() + "; domain="
					+ sessionCookie.getDomain();
			cookieManager.setCookie(L.baseDomain, cookieString);
			CookieSyncManager.getInstance().sync();
		}
		Bundle bundle = this.getIntent().getExtras();
		String URL = "";
		String lx = bundle.getString(L.LX);
		if (L.Nine.GW.endsWith(lx)||L.Nine.XW.equals(lx)) {
			String zt = bundle.getString(L.ZT);
			URL = L.gwListWapUrl + "&ZT=" + zt + "&CZRY_DM="
					+ L.status.get("CZRY_DM") + "&JSESSIONID="
					+ L.status.get("JSESSIONID");
		} else if (L.Nine.DZGG.endsWith(lx)) {
			URL = L.dzggUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
					+ "&JSESSIONID=" + L.status.get("JSESSIONID");
		} else if (L.Nine.DZYX.endsWith(lx)) {
			HttpPost request = new HttpPost(L.mailAuthUrl);
			JSONObject param = new JSONObject();
			try {
				/* param.put("userId", userN.getText().toString()); */
				param.put("LOG_CZRY_DM", L.status.get("CZRY_DM"));
				StringEntity se = new StringEntity(param.toString());
				request.setEntity(se);
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(request);
				String retSrc = EntityUtils.toString(httpResponse.getEntity());

				System.out.println(retSrc);
				JSONObject result = new JSONObject(retSrc);

				if ("0".equals(result.getString("ret_code"))) {
					URL = "http://nymail.htjs.net/mh/listfolder.jsp?sessionid="
							+ result.getString("sessionid");
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			URL = L.dzyxUrl + "sessionid=" + L.status.get("JSESSIONID");
		} else if (L.Nine.GZZD.endsWith(lx)) {
			URL = L.gzzdUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
					+ "&JSESSIONID=" + L.status.get("JSESSIONID");
		} else if (L.Nine.TXL.endsWith(lx)) {
			URL = L.txlUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
					+ "&JSESSIONID=" + L.status.get("JSESSIONID");
		}

		webView.loadUrl(URL, L.status);
		System.out.println(L.cookie);
	}

	class GetListHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();// 关闭进度条
		}
	}
	
	private void download() {
        // 获取SD卡目录
        String dowloadDir = Environment.getExternalStorageDirectory()
                + "/ideasdownload/";
        File file = new File(dowloadDir);
        //创建下载目录
        if (!file.exists()) {
            file.mkdirs();
        }
 
        //读取下载线程数，如果为空，则单线程下载
        int downloadTN = Integer.valueOf("".equals(downloadThreadNum.getText()
                .toString()) ? "1" : downloadThreadNum.getText().toString());
        //如果下载文件名为空则获取Url尾为文件名
        int fileNameStart = downloadUrl.getText().toString().lastIndexOf("/");
        String fileName = "".equals(downloadFileName.getText().toString()) ? downloadUrl
                .getText().toString().substring(fileNameStart)
                : downloadFileName.getText().toString();
        //开始下载前把下载按钮设置为不可用
        downloadBt.setClickable(false);
        //进度条设为0
        downloadProgressBar.setProgress(0);
        //启动文件下载线程
        new downloadTask(downloadUrl.getText().toString(), Integer
                .valueOf(downloadTN), dowloadDir + fileName).start();
    }
 
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //当收到更新视图消息时，计算已完成下载百分比，同时更新进度条信息
            int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue();
            if (progress == 100) {
                downloadBt.setClickable(true);
                progressMessage.setText("下载完成！");
            } else {
                progressMessage.setText("当前进度:" + progress + "%");
            }
            downloadProgressBar.setProgress(progress);
        }
 
    };
    private EditText downloadUrl;
    private EditText downloadFileName;
    private EditText downloadThreadNum;
    private Button downloadBt;
    private ProgressBar downloadProgressBar;
    private TextView progressMessage;
    private int downloadedSize = 0;
    private int fileSize = 0;
    /**
     * @author ideasandroid
     * 主下载线程
     */
    public class downloadTask extends Thread {
        private int blockSize, downloadSizeMore;
        private int threadNum = 5;
        String urlStr, threadNo, fileName;
 
        public downloadTask(String urlStr, int threadNum, String fileName) {
            this.urlStr = urlStr;
            this.threadNum = threadNum;
            this.fileName = fileName;
        }
 
        @Override
        public void run() {
            FileDownLoadThread[] fds = new FileDownLoadThread[threadNum];
            try {
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                //获取下载文件的总大小
                fileSize = conn.getContentLength();
                //计算每个线程要下载的数据量
                blockSize = fileSize / threadNum;
                // 解决整除后百分比计算误差
                downloadSizeMore = (fileSize % threadNum);
                File file = new File(fileName);
                for (int i = 0; i < threadNum; i++) {
                    //启动线程，分别下载自己需要下载的部分
                	FileDownLoadThread fdt = new FileDownLoadThread(url, file,
                            i * blockSize, (i + 1) * blockSize - 1);
                    fdt.setName("Thread" + i);
                    fdt.start();
                    fds[i] = fdt;
                }
                boolean finished = false;
                while (!finished) {
                    // 先把整除的余数搞定
                    downloadedSize = downloadSizeMore;
                    finished = true;
                    for (int i = 0; i < fds.length; i++) {
                        downloadedSize += fds[i].getDownloadSize();
                        if (!fds[i].isFinished()) {
                            finished = false;
                        }
                    }
                    //通知handler去更新视图组件
                    handler.sendEmptyMessage(0);
                    //休息1秒后再读取下载进度
                    sleep(1000);
                }
            } catch (Exception e) {
 
            }
 
        }
    }
}
